What is ansi-regex?
The ansi-regex npm package is used to create regular expressions to match ANSI escape codes, which are used to format output in terminal with colors, background colors, styles like bold or underline, and other text effects.
What are ansi-regex's main functionalities?
Matching ANSI escape codes
This code sample demonstrates how to use ansi-regex to match ANSI escape codes in a string. The string contains the ANSI escape codes for underlining text, followed by the word 'cake', and then the reset code to stop the underlining. The ansiRegex function is called to generate a regular expression that matches these codes.
"\u001B[4mcake\u001B[0m".match(ansiRegex());
Other packages similar to ansi-regex
strip-ansi
strip-ansi is a package that removes ANSI escape codes from strings. It is similar to ansi-regex in that it deals with ANSI codes, but instead of matching them, it strips them from the text, which can be useful for cleaning up terminal output for logging or processing.
chalk
chalk is a popular package for styling terminal output with ANSI escape codes. It provides a more user-friendly API for applying styles compared to manually writing escape codes. While ansi-regex is used for detecting ANSI codes, chalk is used for generating them.
ansi-regex
Regular expression for matching ANSI escape codes
Install
$ npm install ansi-regex
Usage
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001B[4mcake\u001B[0m');
ansiRegex().test('cake');
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
FAQ
Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
Maintainers
License
MIT